package com.ljh.webtask5.controller;

import com.ljh.webtask5.Exception.NotFoundException;
import com.ljh.webtask5.mybatisplus.entity.Book;
import com.ljh.webtask5.mybatisplus.mapper.BookMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author laijiahong
 */
@Controller
@Tag(name = "WebTask5", description = "图书管理")
@RequestMapping("/api/v1/book")
public class BookController {
    @Resource
    BookMapper bookMapper;

    @Operation(summary = "获取图书列表", description = "返回图书列表视图，其中包含全部图书的列表")
    @GetMapping(value = "")
    @ResponseStatus(HttpStatus.OK)
    public String getBookList(Model model) {
        List<Book> bookList = bookMapper.selectList(null);
        model.addAttribute("bookList", bookList);
        return "BookList";
    }

    @Operation(summary = "返回登记图书视图")
    @GetMapping("/registration")
    @ResponseStatus(HttpStatus.OK)
    public String registerForm() {
        return "Registration";
    }

    @Operation(summary = "添加新的图书")
    @PostMapping("")
    @ResponseStatus(HttpStatus.OK)
    public String register(@RequestParam String bookName,
                           @RequestParam String author,
                           @RequestParam String press,
                           @RequestParam String publicDate,
                           @RequestParam int surplus) {
        Book book = new Book(bookName, author, press, publicDate, surplus);
        bookMapper.insert(book);
        return "redirect:/api/v1/book";
    }

    @Operation(summary = "根据id删除图书", description = "如果不存在，则返回状态码404")
    @DeleteMapping("/{id}")
    public String delete(@PathVariable Long id) {
        if (bookMapper.deleteById(id) <= 0) {
            throw new NotFoundException();
        }
        return "redirect:/api/v1/book";
    }

    @Operation(summary = "返回登记图书视图")
    @GetMapping("/edit")
    @ResponseStatus(HttpStatus.OK)
    public String editForm(Model model, @RequestParam Long index) {
        Book book = bookMapper.selectById(index);
        model.addAttribute("book", book);
        return "Edit";
    }

    @Operation(summary = "根据id修改图书信息", description = "如果不存在，则返回状态码404")
    @PutMapping("/{id}")
    public String edit(@PathVariable Long id, @ModelAttribute Book book) {
        book.setIndex(id);
        if (bookMapper.updateById(book) <= 0) {
            throw new NotFoundException();
        }
        return "redirect:/api/v1/book";
    }
}
